import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';


import { routerShape } from 'react-router';
import isEmpty from 'lodash/isEmpty'
import { WeaTableNew } from 'comsMobx';
import { WeaForm, WeaSwitch } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import {
    WeaTop,
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaFormItem
} from 'ecCom'

import { WeaErrorPage, WeaTools, WeaCheckbox } from 'ecCom'
import { Button, Form, Modal } from 'antd'
const createForm = Form.create;
const FormItem = Form.Item;
let _this = null;
import MeetingDialog from '../public/dialog/index';
import RoomPlanDialog from '../public/roomPlan/index';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

@inject('meetingDecision')
@inject('meetingDialog')
@observer
class Decision extends React.Component {
    static contextTypes = {
        router: routerShape
    }
    constructor(props) {
        super(props);
        _this = this;
        this.state = {
            RoomPlanContainer: false,
            dialogType: 'preview',
            meetingId: '',
            visible: false,
        }
    }
    componentDidMount() {//一些初始化请求
        const { meetingDecision } = this.props;
        //初始化高级搜索区域
        meetingDecision.initDatas();
        //初始化列表
        meetingDecision.doLoading();
    }
    componentWillReceiveProps(nextProps) {
        if(this.props.location.key !== nextProps.location.key) {
            const { meetingDecision } = this.props;
            //初始化列表
            meetingDecision.doLoading({
                deciScope: meetingDecision.deciScope,
                ...meetingDecision.adSearchForm.getFormParams()
            });
        }
    }

    componentWillUnmount() {
        //组件卸载时一般清理一些状态
        const { meetingDecision } = this.props;
        meetingDecision.showSearchAd = false;
    }

    
    render() {
        let { RoomPlanContainer, visible, dialogType, meetingId } = this.state;
        const { meetingDecision } = this.props;
        const { loading, title, conditioninfo, showSearchAd, searchParamsAd, dataKey, topTab, previewMeetingId } = meetingDecision;
        let { dialogStatus, doInit, onlyClose, setRoomPlan } = this.props.meetingDialog;
        let { dialogTitle, type, zIndex } = toJS(dialogStatus);
        let collectParams={
            favname: title,
            favouritetype: 5,
            objid: 0,
            importantlevel: 1,
        };
        return (
            <div className="metting-search">

                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@auabth`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}  
                    collectParams={collectParams}>
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jbksd4`}
                        title={title}
                        loading={loading}
                        icon={<i className='icon-coms-meeting' />}
                        iconBgcolor='#f14a2d'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()}
                        onDropMenuClick={this.onRightMenuClick}
                        dropMenuProps={{collectParams: collectParams}
                        }
                    >
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@afcwzf`}
                            buttonsAd={this.getTabButtonsAd()}
                            searchsBaseValue={meetingDecision.adSearchForm.getFormParams()['subjects']}
                            searchType={['base', 'advanced']}
                            setShowSearchAd={bool => { meetingDecision.setShowSearchAd(bool) }}
                            hideSearchAd={() => meetingDecision.setShowSearchAd(false)}
                            advanceHeight='265px'
                            searchsAd={<Form ecId={`${this && this.props && this.props.ecId || ''}_Form@rcbt7y`} horizontal>{this.getSearchs()}</Form>}
                            showSearchAd={showSearchAd}
                            onSearch={v => {
                                meetingDecision.doLoading(
                                    {
                                        deciScope: meetingDecision.deciScope,
                                        ...meetingDecision.adSearchForm.getFormParams()
                                    }
                                )
                            }}
                            onSearchChange={v => {
                                meetingDecision.adSearchForm.updateFields(
                                    {
                                        subjects: {
                                            value: v
                                        }
                                    },
                                    true
                                );
                            }}
                            selectedKey={meetingDecision.deciScope ? meetingDecision.deciScope : 0}
                            keyParam="viewcondition"  //主键
                            countParam="groupid" //数量
                            onChange={this.changeData}
                            datas={topTab}
                        />
                        {
                            loading ? '' :meetingDecision.tableStore[dataKey]?
                                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@l761ro`}
                                    hasOrder={true}
                                    needScroll={true}
                                    onOperatesClick={this.getOperatesClick}
                                    getColumns={this.getColumns}
                                    sessionkey={dataKey} 
                                    comsWeaTableStore={meetingDecision.tableStore[dataKey]}
                                />:''
                        }
                    </WeaTop>
                </WeaRightMenu>
                {/*<PreviewMeeting*/}
                {/*meetingId = {previewMeetingId}*/}
                {/*onClose={(meetingid='')=>{meetingDecision.savePreviewMeetingId({meetingid:meetingid})}}*/}
                {/*/>*/}
                <MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@2ar40k`}
                    setRoomPlan={this.setRoomPlan}
                    setDialog={this.setDialog}
                    setType={this.setType}
                    setMeetingId={this.setMeetingId}
					setAll={this.setAll}

                    type={dialogType}//新建为'create',查看为'preview',编辑edit,会议决议---待定
                    visible={visible}//显隐受控
                    doRefesh={this.doRefesh}//自定义刷新页面，不会关掉弹出框
                    meetingId={meetingId} //会议id，查看会议时用到
                    isInterval={false}//新建会议类型，true是周期会议， false是普通会议
                    meetingDate={''}//新建日期

                /> 

                {RoomPlanContainer && <RoomPlanDialog ecId={`${this && this.props && this.props.ecId || ''}_RoomPlanDialog@iv92vs`}
                    setRoomPlan={this.setRoomPlan}
                    setDialog={this.setDialog}
                    setType={this.setType}
                    setMeetingId={this.setMeetingId}
                    canCreate={false}
                    height={600}
                    visible={RoomPlanContainer} />}

            </div>
        )
    }
    doRefesh = () => {

    }
 
    setAll = (meetingId, bool, type)=>{
		this.setState({
			meetingId:meetingId,
			visible:bool,
			dialogType:type
		})
	}
    setMeetingId = (meetingId) => {
        this.setState({ meetingId: meetingId })
    }
    setRoomPlan = (bool) => {
        this.setState({ RoomPlanContainer: bool })
    }
    setDialog = (bool) => {
        this.setState({ visible: bool })
    }
    setType = (type) => {
        this.setState({ dialogType: type })
    }

    //右键菜单事件绑定
    onRightMenuClick = (key)=>{
        const { meetingDecision } = this.props;
        const { searchParamsAd } = this.props;
        const { tableStore,dataKey } = meetingDecision;
        if (key == '0') {
            meetingDecision.doLoading({
                ...meetingDecision.adSearchForm.getFormParams(),
                deciScope: meetingDecision.deciScope,
            });
            meetingDecision.setShowSearchAd(false)
        } else if (key == '1') {
            meetingDecision.doLoading();
            meetingDecision.setShowSearchAd(false);
            meetingDecision.adSearchForm.reset();
        } else if(key=='BTN_COLUMN'){
                tableStore[dataKey].setColSetVisible(true);
    		    tableStore[dataKey].tableColSet(true);
        }

    }

    getColumns = (columns) => {
        let newColumns = '';
        newColumns = columns.map(column => {
          let newColumn = column;
          newColumn.render = (text, record, index) => { //前端元素转义
            let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
            return (
              newColumn.dataIndex == 'name' ?
                <a onClick={() => {
                  this.setState({meetingId: record.meetingid, visible: true})
                }} dangerouslySetInnerHTML={{ __html: valueSpan }} />
                :
                <div dangerouslySetInnerHTML={{ __html: valueSpan }} />
            )
          }
          return newColumn;
        });
        return newColumns;
    }

    //右键菜单
    getRightMenu() {
        let btns = [];
        btns.push({
            icon: <i className='icon-coms-search' />,
            content: getLabel(82529,"搜索")
        });
        btns.push({
            key: 'BTN_COLUMN',
            icon: <i className='icon-coms-Custom'/>,
            content : `${getLabel(32535,'显示列定制')}`,
            onClick : () => this.onRightMenuClick('BTN_COLUMN')
        });
        return btns
    }
    //高级搜索group定义
    getSearchs() {
        const { meetingDecision } = this.props;
        const conditioninfo = meetingDecision.conditioninfo;
        const { adSearchForm } = meetingDecision;
        const { isFormInit } = adSearchForm;
        let group = [];
        isFormInit && conditioninfo.map((c, index) => {
            let items = [];
            c.items.map(fields => {
                items.push({
                    com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ev8us8@${fields.domkey[0]}`}
                        label={`${fields.label}`}
                        labelCol={{ span: `${fields.labelcol}` }}
                        wrapperCol={{ span: `${fields.fieldcol}` }}>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@za66v2@${fields.domkey[0]}`} fieldConfig={fields} form={adSearchForm} onChange={null/*todo*/} onEnterSearch={this.onEnterSearch}/>
                    </WeaFormItem>),
                    colSpan: 1
                })
            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@voyxvm@${index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
        });
        return group;
    }

    onEnterSearch = ()=>{
        const { meetingDecision } = this.props;
        meetingDecision.doLoading({
            ...meetingDecision.adSearchForm.getFormParams(),
            deciScope: meetingDecision.deciScope,
        });
        meetingDecision.setShowSearchAd(false)
    }

    getTitle(index = 0) {
        const { meetingDecision } = this.props;
        const { conditioninfo } = meetingDecision;
        return !isEmpty(conditioninfo) && conditioninfo[index].title
    }
    isShowFields(index = 0) {
        const { meetingDecision } = this.props;
        const { conditioninfo } = meetingDecision;
        if (conditioninfo.length == 0) {
            return true;
        }
        return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const { meetingDecision } = this.props;
        const { conditioninfo } = meetingDecision;
        const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
        let items = [];
        // forEach(fieldsData, (field) => {
        //     items.push({
        //         com:(<FormItem
        //             label={`${field.label}`}
        //             labelCol={{span: `${field.labelcol}`}}
        //             wrapperCol={{span: `${field.fieldcol}`}}>
        //             {WeaTools.switchComponent(this.props, field.key, field.domkey, field)}
        //         </FormItem>),
        //         colSpan:1
        //     })
        // todo
        // })
        return items;
    }
    //高级搜索底部按钮定义
    getTabButtonsAd() {
        const { meetingDecision } = this.props;
        const { searchParamsAd } = meetingDecision;
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m1u0ob@doSearch`} type="primary" onClick={() => {
                meetingDecision.doLoading({
                    ...meetingDecision.adSearchForm.getFormParams(),
                    deciScope: meetingDecision.deciScope,
                });
                meetingDecision.setShowSearchAd(false)
            }}>{getLabel(82529,"搜索")}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uoon2v@doReset`} type="ghost" onClick={() => { meetingDecision.adSearchForm.reset() }}>{getLabel(2022,"重置")}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l53nhi@doCancel`} type="ghost" onClick={() => { meetingDecision.setShowSearchAd(false) }}>{getLabel(201,"取消")}</Button>)
        ]
    }
    getButtons() {
        let btns = [];
        return btns
    }
    changeData = (theKey)=>{
        const { meetingDecision } = this.props;
        // const {searchParamsAd,fields} = meetingDecision;
        meetingDecision.setShowSearchAd(false);
        meetingDecision.deciScope = theKey;
        meetingDecision.adSearchForm.reset();
        // meetingDecision.adSearchForm.updateFields({...fields,deciScope:{name:'deciScope',value:theKey}});
        meetingDecision.doLoading({ deciScope: meetingDecision.deciScope });
    }
    getOperatesClick = (record, index, operate, flag) => {
        const { meetingDecision } = this.props;
        // const {searchParamsAd} = meetingDecision;
        let id = record.id;
        let idspan = record.idspan;
        let contentDom = null;
        const style1 = {
            paddingBottom: '10px',
            paddingLeft: '0px',
            paddingTop: '15px'
          };
          const style2 = {
            paddingBottom: '15px'
          };
        //获取record中的数据判断是否为检查人
        let mycheck = '0';
        let operateType = operate.index;
            if (operateType == 0) {
                if(idspan == 'true'){
                    contentDom = (
                        <div>
                          <div class='ant-confirm-content wdb wea-f14' style={ style1 }>{getLabel(387046,'确认完成吗？')}</div>
                          <div style={style2}>
                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@rp75xv`} 
                              value = { mycheck }
                              onChange={value => {
                                mycheck = value;
                            }}/>
                            <span style={{ fontSize: '14px',paddingLeft: '7px' }}>{getLabel('520393','给执行人发送完成的消息中心提醒')}</span></div>
                        </div>
                      )
                }else{
                    contentDom = (
                        <div>
                          <div class='ant-confirm-content wdb wea-f14' style={ style1 }>{getLabel(387046,'确认完成吗？')}</div>
                          <div style={style2}>
                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@tdqetk`} 
                              value = { mycheck }
                              onChange={value => {
                                mycheck = value;
                            }}/>
                            <span style={{ fontSize: '14px',paddingLeft: '7px' }}>{getLabel('520394','给检查人发送完成的消息中心提醒')}</span></div>
                        </div>
                      )
                }
                Modal.confirm({
                    title: `${getLabel(131329,'信息确认')}`,
                    content: contentDom,
                    onOk() {
                        let allparams = { id: id,isRemind: mycheck};
                        meetingDecision.Done(allparams, 
                            { ...meetingDecision.adSearchForm.getFormParams() }
                        );
                    },
                    onCancel() { },
                });
                // meetingDecision.Done({ id }, { ...meetingDecision.adSearchForm.getFormParams() });
            }
        //});

    }

}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return (
            <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@1u1xrt`} msg={hasErrorMsg ? this.props.error : getLabel(383324,"对不起，该页面异常，请联系管理员")} />
        );
    }
}

Decision = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Decision);

export default Decision
